package org.cms;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.cms.annotation.GooglePlus;
import org.cms.call.GetNewTokenCall;
import org.cms.call.GetUserInfoCall;
import org.cms.raw.calendar.EventRaw;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 *
 *
 */
@GooglePlus
public class GooglePlusFacade implements IUserProfileService<EventRaw> {

    private static final String CLIENT_ID = "170966694283-mf1ovt38epobmj622gi20v0diq6i6bhv.apps.googleusercontent.com";
    private static final String CLIENT_SECRET = "uDDpNQziXRjWoN1-NfMmjNdQ";


    Logger log = Logger.getLogger("GooglePlusFacade");

    private PropertiesHandler tokenProperties = new PropertiesHandler("calendar_tokens.properties");

    /**
     * Retrive a list of event for a specific user
     *
     * @return the list of Events
     * @throws java.io.IOException
     * @throws org.json.JSONException
     */
    @Override
    public List<EventRaw> getUserProfile() {


        HttpClient httpclient = HttpClients.createDefault();
        String refreshToken = "UNDEFINED";
        String access_token = "UNDEFINED";

        List<EventRaw> eventRawList = new ArrayList<EventRaw>();

        boolean refreshed = false;
        boolean changed = false;
        try {

            for (String key : tokenProperties.stringPropertyNames()) {
                refreshToken = key;
                access_token = tokenProperties.getProperty(key);

                GetUserInfoCall userInfoCall = new GetUserInfoCall(httpclient, access_token).invoke();
                // Refresh Token
                if (userInfoCall.getResponse().getStatusLine().getStatusCode() != 200) {

                    //consume the failed response
                    EntityUtils.consume(userInfoCall.getResponse().getEntity());
                    access_token = new GetNewTokenCall(httpclient, refreshToken, CLIENT_ID, CLIENT_SECRET).invoke().getNewAccessToken();
                    refreshed = true;
                    tokenProperties.setProperty(refreshToken, access_token);
                    changed = true;
                }
                if (refreshed) {
                    userInfoCall = new GetUserInfoCall(httpclient, access_token).invoke();
                }
                String output = userInfoCall.getResponseContentAsString();

                JSONObject json = new JSONObject(output);
                System.out.println(output);
                String userId = json.getString("id");

//                GetEventsCall getEventsCall = new GetEventsCall(access_token, userId, httpclient).invoke();
//
//                String eventsAsString = getEventsCall.getResponseContentAsString();
//                JSONArray eventsJson = new JSONObject(eventsAsString).getJSONArray("items");
//
//                Gson gson = new GsonBuilder().create();
//                log.info("iterating over " + eventsJson.length() + " events");
//
//                for (int i = 0; i < eventsJson.length(); i++) {
//                    JSONObject event = eventsJson.getJSONObject(i);
//                    EventRaw event1 = gson.fromJson(event.toString(), EventRaw.class);
//                    log.info("EVENT captured : " + eventRawList.add(event1));
//
//                }
            }
            if (changed) {
                tokenProperties.updateProperties();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }

        return eventRawList;

    }
}

